<?php
namespace app\job;

use app\api\controller\v1\Clue as ClueModel;
use think\Db;
use think\Exception;
use think\Queue;
use think\queue\Job;

//php think queue:listen --queue CluePriceAdmin
//第一部。商务管理员成本
class CluePriceAdmin{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function doHelloJob($data) {
        try {
            $map1['clue_time']=$data['time'];
            $map2['a.create_time']=$data['time'];
            Db::name('admin_clue_price')->where($map1)->delete();

            $list=Db::name('clue')->alias('a')->field('a.id,a.price,true_price,status,create_time')
                ->where($map2)->chunk(100,function($users) {
                    $log=[];
                    foreach ($users as $user) {
                       if($user['status']==1){

                           $bind_user=Db::name('clue_log')->alias('a')->field('a.mer_id,a.push_id,b.bind_aid')
                               ->join('merchant b','b.id=a.mer_id')
                               ->where('a.clue_id',$user['id'])->find();
                           $log[]=['clue_id'=>$user['id'],'mer_id'=>$bind_user['mer_id'],'push_id'=>$bind_user['push_id'],'admin_id'=>$bind_user['bind_aid'],'price'=>$user['price'],'true_price'=>$user['true_price'],'create_time'=>time(),'clue_time'=>$user['create_time']];
                       }else{
                           $merArr=Db::name('admin_clue_mer')->where('clue_id',$user['id'])->column('mer_id');
                           if(empty($merArr)){
                               $log[]=['clue_id'=>$user['id'],'mer_id'=>0,'push_id'=>0,'admin_id'=>0,'price'=>$user['price'],'true_price'=>$user['true_price'],'create_time'=>time(),'clue_time'=>$user['create_time']];
                           }else{
                               $merArr=array_unique($merArr);
                               if(count($merArr)==1&&$merArr[0]==0){
                                   $log[]=['clue_id'=>$user['id'],'mer_id'=>0,'push_id'=>0,'admin_id'=>0,'price'=>$user['price'],'true_price'=>$user['true_price'],'create_time'=>time(),'clue_time'=>$user['create_time']];
                               }else{
                                   $admin=Db::name('merchant')->whereIn('id',$merArr)->column('bind_aid');
                                   $adrminArr=array_unique($admin);
                                   if(in_array(0,$adrminArr)){
                                       $adminNum=count($adrminArr)-1;
                                       $moneyPrice=round(bcdiv($user['price'],$adminNum,3),2);
                                       $moneyPrice2=round(bcdiv($user['true_price'],$adminNum,3),2);
                                       foreach ($adrminArr as $vv){
                                           if($vv!=0){
                                               $log[]=['clue_id'=>$user['id'],'mer_id'=>0,'push_id'=>0,'admin_id'=>$vv,'price'=>$moneyPrice,'true_price'=>$moneyPrice2,'create_time'=>time(),'clue_time'=>$user['create_time']];
                                           }
                                       }
                                   }else{
                                       $adminNum=count($adrminArr);
                                       $moneyPrice=round(bcdiv($user['price'],$adminNum,3),2);
                                       $moneyPrice2=round(bcdiv($user['true_price'],$adminNum,3),2);
                                       foreach ($adrminArr as $vv){
                                           $log[]=['clue_id'=>$user['id'],'mer_id'=>0,'push_id'=>0,'admin_id'=>$vv,'price'=>$moneyPrice,'true_price'=>$moneyPrice2,'create_time'=>time(),'clue_time'=>$user['create_time']];
                                       }
                                   }

                               }
                           }
                       }
                    }

                    if(!empty($log)){
                        Db::name('admin_clue_price')->insertAll($log);
                    }
                });
            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            $jobHandlerClassName  = 'app\job\ClueLossPriceAdmin@fire';
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "ClueLossPriceAdmin";

            $jobData = ['time'=>$data['time']];//时间戳

            $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
            return true;
        }catch (Exception $e){
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return true;
        }
    }

}